<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
use Spatie\EloquentSortable\Sortable;
use Spatie\EloquentSortable\SortableTrait;

/**
 * @property int $id
 * @property string $name
 * @property int $question_count
 * @property int $selected_count
 * @property int $order
 */
class Category extends Model implements Sortable
{
    use SortableTrait;

    // 缓存键名
    const CACHE_KEY = 'categories';

    /**
     * 排序
     *
     * @var array
     */
    protected $sortable = [
        // 设置排序字段名称
        'order_column_name' => 'order',
        // 是否在创建时自动排序，此参数建议设置为true
        'sort_when_creating' => true,
    ];

    /**
     * {@inheritdoc}
     */
    protected static function boot()
    {
        parent::boot();

        // 分类更新后删除缓存
        static::saved(function () {
            Cache::forget(self::CACHE_KEY);
        });
    }

    /**
     * 取出全部分类并永久缓存，分类更新后会删除缓存，参考 boot()
     *
     * @return \Illuminate\Database\Eloquent\Collection
     */
    public static function getFromCache()
    {
        return Cache::rememberForever(self::CACHE_KEY, function () {
            return static::all();
        });
    }

    /**
     * 统计各分类题目数
     */
    public static function refreshQuestionCount()
    {
        Question::query()
            ->selectRaw('category_id, COUNT(*) as count')
            ->groupBy('category_id')
            ->pluck('count', 'category_id')
            ->map(function ($count, $id) {
                static::query()->where('id', $id)->update(['question_count' => $count]);
            });

        // 分类更新后删除缓存
        Cache::forget(self::CACHE_KEY);
    }

    /**
     * 考题
     *
     * @return \Illuminate\Database\Eloquent\Relations\hasMany
     */
    public function questions()
    {
        return $this->hasMany(Question::class);
    }
}
